﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Messaging;
/// <summary>
/// MqUtil 的摘要说明
/// </summary>
public static class MqUtil
{
    static IMessageFormatter formatter = new System.Messaging.BinaryMessageFormatter();

    private static System.Messaging.Message CreateMessage(string text, string label, IMessageFormatter formatter)
    {
        System.Messaging.Message message = new System.Messaging.Message();
        message.Body = text;
        message.Label = label;
        message.Formatter = formatter;
        return message;
    }

    private static void CreateMessageQueue(string queuePath)
    {
        if (!MessageQueue.Exists(queuePath))
        {
            MessageQueue queue = MessageQueue.Create(queuePath, true);
            queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
            queue.Label = queuePath;
        }
    }

    /// <summary>
    /// 发送到队列中
    /// </summary>
    /// <param name="quenePath">队列</param>
    /// <param name="reckey">数据主标识</param>
    /// <param name="label">标签</param>
    public static string Send2Quene(string quenePath, string reckey, string recbody)
    {
        string messageId = string.Empty;

        CreateMessageQueue(quenePath);

        System.Messaging.Message message = CreateMessage(recbody, reckey, formatter);

        MessageQueue queue = new System.Messaging.MessageQueue(quenePath);

        MessageQueueTransaction transaction = new MessageQueueTransaction();
        try
        {
            if (queue.Transactional)
                transaction.Begin();

            queue.Send(message, transaction);

            if (queue.Transactional)
                transaction.Commit();
        }
        catch (Exception ex)
        {
            if (queue.Transactional)
                transaction.Abort();

            throw;
        }
        messageId = message.Id;

        return messageId;
    }

}